﻿using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Services.EntityServices.Customers;
using PMS.Services.EntityServices.Logging;
using PMS.Services.EntityServices.Messages;
using System;

namespace PMS.Services.Utils.ScheduleTasks
{
    /// <summary>
    /// Send Greeting Email to Customers of BirthDay
    /// </summary>
    public partial class BatchSendBirthdayEmailTask: IScheduleTask
    {
        #region Fields

        private readonly ILogger _logger;
        private readonly ICustomerService _customerService;
        private readonly IWorkflowMessageService _workflowMessageService;

        #endregion

        #region Ctor

        public BatchSendBirthdayEmailTask(ILogger logger,
            ICustomerService customerService,
            IWorkflowMessageService workflowMessageService)
        {
            _logger = logger;
            _customerService = customerService;
            _workflowMessageService = workflowMessageService;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Executes a task
        /// </summary>
        public bool Execute()
        {
            DateTime today = DateTime.Today;
            var registedRole = _customerService.GetCustomerRoleByRoleType(RoleType.Guests);
            if (registedRole == null) return false;
            //基于Aliyun Email每天邮天免费邮件数为200,故发送生日祝福邮件数量在此做限制
            //后期根据业务实际需求进行调整
            var searchTodayBirthdayCustomers = _customerService.GetAllCustomers(customerRoleIds: new int[] { registedRole.Id },
                dayOfBirth: today.Day, 
                monthOfBirth: today.Month, 
                pageIndex: 0, 
                pageSize: 100);
            if (searchTodayBirthdayCustomers.TotalCount <= 0) return true;
            var greetingEmailIds = _workflowMessageService.SendBirthdayGreetingEmail(searchTodayBirthdayCustomers);
            _logger.Information($"BatchSendBirthdayEmailTask Executed Success: Birthday of Customers on: {today.ToString("MM-dd")} has count of: {searchTodayBirthdayCustomers.TotalCount}, And Email sended has count of: {greetingEmailIds.Count}");
            return true;
        }

        #endregion
    }
}
